import 'package:homepad/iot/basic_types.dart';
import 'package:homepad/iot/message_def.dart';
import 'package:homepad/logger/logger.dart';

import 'basic_node.dart';

class LightOnOff extends BasicNode {
  LightOnOff.fromJson(super.json) : super.fromJson();

  var onOff = false;
  var _lastOnOff = false;

  @override
  String get desc {
    if (!reachable) {
      return super.desc;
    }
    return onOff ? "开" : "关";
  }

  @override
  BasicNodeState get state {
    if (!reachable) {
      return super.state;
    }
    return _lastOnOff ? BasicNodeState.activated : BasicNodeState.normal;
  }

  @override
  void toggle() {
    setOnOff(!_lastOnOff);
  }

  @override
  void readAllState() {
    readAttribute(ClusterIds.onOff, OnOffAttributeIds.onOff);
  }

  @override
  bool onAttributeReport(AttributePathIB path, data) {
    logger.info("$name data: $data");
    if (path.cluster != ClusterIds.onOff) {
      return super.onAttributeReport(path, data);
    }

    if (path.attribute == OnOffAttributeIds.onOff) {
      var newValue = data as bool;
      if (newValue == onOff) {
        return false;
      }
      _lastOnOff = newValue;
      onOff = newValue;
      return true;
    }
    return false;
  }

  void setOnOff(bool value) {
    _lastOnOff = value;
    onOff = value;
    logger.info("$name endpoint:$endpointId setOnOff: $_lastOnOff");
    delegate.onStateChanged("ep:$endpointId}+$value");
    delegate.onAttributeSet(
        AttributePathIB(
            endpoint: endpointId, cluster: ClusterIds.onOff, attribute: OnOffAttributeIds.onOff),
        value);
  }
}
